package com.fyzs.mp3recorder

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.media.*
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.text.format.DateFormat
import android.text.format.DateUtils
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.core.app.ActivityCompat
import com.fyzs.mp3recorder.wav.Pcm2Wav
import java.io.*
import java.nio.ShortBuffer
import java.text.SimpleDateFormat
import java.util.*

@SuppressLint("MissingPermission")
class AudioRecorderFragment : Fragment(), AudioRecord.OnRecordPositionUpdateListener {


    val TAG = "AudioRecorderFragment"


    val recordThread = HandlerThread("recording").apply { start() }
    val recordHandler = Handler(recordThread.looper)

    companion object{
        const val SAMPLE_RATE=44100
    }


    lateinit var mStateTv: TextView
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_media_record, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mStateTv = view.findViewById(R.id.record_state)


        view.findViewById<Button>(R.id.start_btn).setOnClickListener { start() }
        view.findViewById<Button>(R.id.stop_btn).setOnClickListener { stop() }
    }


    val audioRecorder: AudioRecord by lazy {
        val source = MediaRecorder.AudioSource.MIC
        val sampleRate = SAMPLE_RATE
        val channelConfig = AudioFormat.CHANNEL_IN_STEREO
        val pcm16 = AudioFormat.ENCODING_PCM_16BIT
        val minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, pcm16)
        val audioRecord = AudioRecord(source, sampleRate, channelConfig, pcm16, minBufferSize)
        audioRecord
    }

    fun stop() {
        audioRecorder.stop()
    }

    fun start() {
        audioRecorder.startRecording()
        val cacheDir = requireActivity().cacheDir
        val mediumDateFormat = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA)
        val fileName = "${mediumDateFormat.format(Date(System.currentTimeMillis()))}.pcm"

        val pcmFile = File(cacheDir, "$fileName")
        if (pcmFile.exists().not()) {
            pcmFile.createNewFile()
        }


        val dataOutputStream = DataOutputStream(pcmFile.outputStream())
        recordHandler.post {
            val shortBuffer = ShortArray(audioRecorder.bufferSizeInFrames)

            //记录PCM原始数据
            while (audioRecorder.recordingState != AudioRecord.RECORDSTATE_STOPPED) {
                //在缓冲区读取 声音帧
                val read = audioRecorder.read(shortBuffer, 0, audioRecorder.bufferSizeInFrames)
                for (i in 0 until read) {
                    dataOutputStream.writeShort(shortBuffer[i].toInt())
                }
            }
            dataOutputStream.flush()
            dataOutputStream.close()

            val pcm2Wav = Pcm2Wav()
            val wavFile = File(cacheDir,"${pcmFile.nameWithoutExtension}.wav")
            pcm2Wav.setOutput(wavFile)
            pcm2Wav.setPcmChannel(2)
            pcm2Wav.setSource(pcmFile)
            pcm2Wav.setPcmFormat(AudioFormat.ENCODING_PCM_16BIT)
            pcm2Wav.setSampleRate(SAMPLE_RATE)

            Log.i(TAG, "start: ${pcm2Wav.start()}")
        }
    }

    override fun onMarkerReached(recorder: AudioRecord?) {
        Log.i(TAG, "onMarkerReached: ")
    }

    override fun onPeriodicNotification(recorder: AudioRecord?) {
        Log.i(TAG, "onPeriodicNotification: ")
    }

}